package servlet;

import dao.NoteDao;
import dao.UsersDao;
import entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * servlet的总体控制器
 */
@WebServlet("*.do")
public class ServletController extends HttpServlet {

    public static String globaluser;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //2、拿到请求名
        String requestName = req.getRequestURI().substring(req.getRequestURI().lastIndexOf("/") + 1,
                req.getRequestURI().lastIndexOf("."));
        //3、根据不同的请求进行不同的逻辑派发
        if ("login".equals(requestName)) {
            try {
                loginService(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if ("reg".equals(requestName)) {
            regService(req, resp);
        } else if ("checkUsername".equals(requestName)) {
            try {
                checkService(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else if("index".equals(requestName)){
            try {
                indexService(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        else if ("search".equals(requestName)) {
            try {
                noteSearch(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void indexService(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        refresh(req,resp);
    }

    private void noteSearch(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException {
        String searchText = req.getParameter("keyboard");
        NoteDao noteDao = new NoteDao();
        //1、把指定表的所有数据查询到，然后绑定到session里面去
        //主体
        if(searchText!=""){
            String sqlFindAll = "select noteid,notetitle,notedate,notereadnum,notetext,notezan,notepic,notetag " +
                    "from note where notetitle like '%" + searchText + "%' or notetag like '%" + searchText + "%'";
            req.getSession().setAttribute("notes", noteDao.findAll(sqlFindAll));
        }else {
            String sqlFindAll = "select noteid,notetitle,notedate,notereadnum,notetext,notezan,notepic,notetag from note";
            req.getSession().setAttribute("notes", noteDao.findAll(sqlFindAll));
        }
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }


    private void checkService(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        //1、获取到你登录输入的用户名和密码
        String username = req.getParameter("uname");
        //2、获取一个传输数据到前台的PrintWriter对象
        PrintWriter printWriter = resp.getWriter();
        //3、创建一个操作数据库的dao对象
        UsersDao dao = new UsersDao();
        //4、调用检查用户名方法
        if (dao.checkUsername(username)) {
            //5、如果用户名不存在，发送数据给前台
            printWriter.write("");
        } else {
            //6、如果用户名已经存在，发送数据给前台
            printWriter.write("用户名已存在");
        }
    }

    private void regService(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1、获取到你登录输入的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String job = req.getParameter("job");
        String introduction = req.getParameter("introduction");
        //2、封装成一个Users对象
        Users users = new Users();
        users.setUsername(username);
        users.setPassword(password);
        users.setJob(job);
        users.setIntroduction(introduction);
        //3、创建一个操作数据库的dao对象
        UsersDao usersDao = new UsersDao();
        //4、调用注册方法
        try {
            usersDao.addUsers(users);
            //5、注册成功，进入登录
            resp.sendRedirect("login.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
            //6、注册失败，那么回到当前页面
            resp.sendRedirect("register.jsp");
        }
    }


    private void loginService(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, ServletException {
        //1、获取到你登录输入的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2、封装成一个Users对象
        Users users = new Users();
        users.setUsername(username);
        users.setPassword(password);
        //3、创建一个操作数据库的dao对象
        UsersDao usersDao = new UsersDao();
        //4、调用登录方法
        if (usersDao.login(users)) {
            globaluser=username;
            //5、登录成功，进入主页面，然后显示，欢迎您,xxx
            req.getSession().setAttribute("users", usersDao.findUser(username));

            refresh(req,resp);
        } else {
            //6、如果登录失败，那么加载一个错误信息，传回登录页面
            req.getSession().setAttribute("hint", "登录失败，用户名或密码错误！");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    //添加数据到主页
    public void refresh(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        NoteDao noteDao = new NoteDao();
        //1、把指定表的所有数据查询到，然后绑定到session里面去
        //主体
        String sqlFindAll = "select noteid,notetitle,notedate,notereadnum,notetext,notezan,notepic,notetag from note";
        req.getSession().setAttribute("notes", noteDao.findAll(sqlFindAll));

        //点击排行
        String sqlFindByReadNum = "select noteid,notetitle,notedate,notereadnum,notetext,notezan,notepic,notetag from note order by notereadnum DESC";
        req.getSession().setAttribute("rank", noteDao.findAll(sqlFindByReadNum));

        //站长推荐
        String sqlFindRecom = "select noteid,notetitle,notedate,notereadnum,notetext,notezan,notepic,notetag from note WHERE noterecom=1 order by notereadnum DESC";
        req.getSession().setAttribute("recom", noteDao.findAll(sqlFindRecom));

        //标签
        req.getSession().setAttribute("tags", noteDao.findTags());
        //5、登录成功，进入主页面，然后显示，欢迎您,xxx
        resp.sendRedirect("index.jsp");
    }
}
